<template>
  <div>
    <el-table
      ref="multipleTable"
      :data="userlist"
      tooltip-effect="dark"
      style="width: 100%"
      @selection-change="handleSelectionChange">
      <el-table-column
        type="selection"
        width="55">
      </el-table-column>
      <el-table-column
        label='序列号'
        type="index"
        width="70">
      </el-table-column>
      <el-table-column
        label="用户名"
        prop='username'
        width="150"
        show-overflow-tooltip
      >
      </el-table-column>
      <el-table-column
        prop="gender"
        label="性别"
        width="80">
      </el-table-column>
      <el-table-column
        prop="age"
        label="年龄"
        width="80">
      </el-table-column>
      <el-table-column
        prop="isSingle"
        label="是否单身"
        width="80">
      </el-table-column>
      <el-table-column
        prop="phone"
        label="电话号码"
        width="200">
      </el-table-column>
      <el-table-column
        label="操作">
        <!-- 通过作用域插槽(子传父)把按钮得到的id传递给父组件 -->
        <template v-slot:default='scope'>
          <!-- {{scope.row}} -->
          <el-button siez='small' plain type="primary" icon="el-icon-edit" circle @click='gotoEdit(scope.row._id)'></el-button>
          <el-button siez='small' plain type="danger" icon="el-icon-delete" circle @click='deleteUser(scope.row._id)'></el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>

export default {
  data(){
    return{
      userlist:[],
      /* 获取id传递给删除、编辑按钮 */
      current:''
    }
  },
  methods:{
    gotoEdit(id){
      this.$router.push('/user/edit/'+id)
    },
    deleteUser(id) {
        this.$confirm('是否删除该用户信息?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          /* 发送删除请求 */
          let {data} = await this.$request.delete('/user/'+id);
          /* 删除成功后过滤用户数据重新渲染 */
          if(data.code===1){
            this.userlist = this.userlist.filter(item=>item._id!==id);
          }
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
      }
      
  },
  async created(){
    let {data} = await this.$request.get('/user');
    this.userlist = data.data;
  }
};
</script>